package com.js.rtu.mvp.present;


import android.util.Log;

import com.js.rtu.base.BasePresenter;
import com.js.rtu.config.AlarmTypeConfig;
import com.js.rtu.fragment.third.DebugReadBean;
import com.js.rtu.mvp.bean.Cmd02Bean;
import com.js.rtu.mvp.bean.Cmd40Bean;
import com.js.rtu.mvp.bean.Cmd90Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.util.BleUtils;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.wandersnail.commons.util.StringUtils;

/**
 * 92查询所有参数数据解析
 * Created by wz on 2019/5/17.
 */
public class Cmd40Presenter implements BasePresenter<Cmd40Bean> {

    int index;

    @Override
    public CommonBean<Cmd40Bean> paseData(String msg) {
        Log.e("40", msg);
        EventBus.getDefault().post(new DebugReadBean(msg));
        CommonBean<Cmd40Bean> bean = new CommonBean<>();
        Cmd40Bean cmd40Bean = new Cmd40Bean();
        index = 0;
        String[] data = msg.split(" ");
        if (getDataByIndex(data, 0).equals("EE") && getDataByIndex(data, 1).equals("EE")
                && getDataByIndex(data, data.length - 1).equals("FF")) {

            //帧头、CRC、帧尾
            bean.setStart(getDataByIndex(data, 0) + getDataByIndex(data, 1));
            bean.setCRC(getDataByIndex(data, data.length - 4) + getDataByIndex(data, data.length - 3));
            bean.setEnd(getDataByIndex(data, data.length - 1) + getDataByIndex(data, data.length - 2));
            index = 2;//2字节


            //address
            StringBuilder str_address = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                str_address.append(getDataByIndex(data, index + i));
            }
            index += 8;//8字节
            String address = BleUtils.hexStr2Str(str_address.toString());
            bean.setAddress(address);

            //length固定长度2，hex
            int length = BleUtils.hToint(getDataByIndex(data, index + 1) + getDataByIndex(data, index));
            index += 2;//2字节
            bean.setLength(length);

            //cmd固定长度1，hex
            int cmd = Integer.parseInt(getDataByIndex(data, index));
            index += 1;//1字节
            bean.setCmd(cmd);
            //这里开始就是data数据

            //报警历史总数，1字节
            cmd40Bean.setTotal(BleUtils.hToint(getDataByIndex(data, index)) + "");
            index += 1;//1字节

            //第2字节为当条信息回传的报警历史数
            cmd40Bean.setCur(BleUtils.hToint(getDataByIndex(data, index)) + "");
            index += 1;//1字节
            //第3字节为每条报警历史的数据长度
            cmd40Bean.setLength(BleUtils.hToint(getDataByIndex(data, index)) + "");
            index += 1;//1字节
//            //第4字节起为报警历史数据包；

            ArrayList<Cmd40Bean.AlarlBean> list = new ArrayList<>();
            for (int i = 0; i < Integer.parseInt(cmd40Bean.getCur()); i++) {
                Cmd40Bean.AlarlBean alarlBean = new Cmd40Bean.AlarlBean();
                alarlBean.setAlarmTime(getTime(data, index));
                index += 6;//6字节


                String type = getType(getDataByIndex(data, index));


                alarlBean.setAlarmType(getType(getDataByIndex(data, index)));

//                alarlBean.setModel(getModel(getDataByIndex(data, index)));
                index += 1;//1字节
                alarlBean.setAlarmTongdao(getDataByIndex(data, index));
                index += 1;//1字节
                if (type.contains("AI")) {
                    //AD值
                    float ad = BleUtils.hToint(getDataByIndex(data, index + 3) +getDataByIndex(data, index + 2) +
                            getDataByIndex(data, index + 1) + getDataByIndex(data, index));

                    float     range = (ad - 800) / 3200;//AD：800-4000对应0-3.7
//
                    if (range <= 0) {
                        range = 0;
                    }
                    if (range >= 1) {
                        range = 1;
                    }

                    float persent=range*100;
                    float curAd=range*600;

                    alarlBean.setAlarmValue(curAd+"(0-600)/"+persent+"%/"+ad+"(800-4000量程)");
                } else if (type.contains("DI")) {
                    alarlBean.setAlarmValue(getDataByIndex(data, index) + getDataByIndex(data, index + 1) + getDataByIndex(data, index + 2) + getDataByIndex(data, index + 3));
                } else {
                    //电池为浮点数
                    String power = BleUtils.byte2Float(getDataByIndex(data, index + 3) + getDataByIndex(data, index + 2)
                            + getDataByIndex(data, index + 1) + getDataByIndex(data, index));

                    alarlBean.setAlarmValue(power);
                }


                index += 4;//4
                list.add(alarlBean);
            }
            cmd40Bean.setAlarlBeans(list);
        }
        bean.setData(cmd40Bean);
        return bean;

    }

    private String getDataByIndex(String[] data, int index) {
        StringBuilder stringBuilder = new StringBuilder();
        if (index < data.length) {
            stringBuilder.append(data[index]).append(" ");
        } else {
            this.index = data.length - 1;
        }
        if (stringBuilder.length() > 0) {
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        } else {
            return stringBuilder.toString();
        }
    }

//    private String getModel(String msg) {
//        String model;
//        int ten = Integer.parseInt(msg, 16);//16--》10
//        String type = Integer.toBinaryString(ten);//10--》2
//        StringBuilder zero = new StringBuilder();
//        for (int i = 0; i < 8 - type.length(); i++) {
//            //补0
//            zero.append("0");
//        }
//        type = zero + type;
////        高四位和第四位分别代表不同的查询条件：
//        String HHHH = type.substring(0, 4);
//
//      return   AlarmTypeConfig.getModel(HHHH)
//
//    }

    private String getType(String msg) {

        int ten = Integer.parseInt(msg, 16);//16--》10
        String type = Integer.toBinaryString(ten);//10--》2
        StringBuilder zero = new StringBuilder();
        for (int i = 0; i < 8 - type.length(); i++) {
            //补0
            zero.append("0");
        }
        type = zero + type;
//        高四位和第四位分别代表不同的查询条件：
        String LLLL = type.substring(4, 8);
        return AlarmTypeConfig.getDes(LLLL);
    }

    /**
     * 获取补调时间
     *
     * @param data  数据
     * @param index 下标
     */
    private String getTime(String[] data, int index) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("20")
                .append(BleUtils.hToint(getDataByIndex(data, index))).append("/")
                .append(String.format(Locale.CHINA, "%02d", BleUtils.hToint(getDataByIndex(data, index + 1)))).append("/")
                .append(String.format(Locale.CHINA, "%02d", BleUtils.hToint(getDataByIndex(data, index + 2)))).append(" ")
                .append(String.format(Locale.CHINA, "%02d", BleUtils.hToint(getDataByIndex(data, index + 3)))).append(":")
                .append(String.format(Locale.CHINA, "%02d", BleUtils.hToint(getDataByIndex(data, index + 4)))).append(":")
                .append(String.format(Locale.CHINA, "%02d", BleUtils.hToint(getDataByIndex(data, index + 5))));

        return stringBuilder.toString();

    }

    public void setInfo(CommonBean<Cmd40Bean> bean) {
        String line = "-----------------------------------------------------------\n";
        Cmd40Bean data = bean.getData();


        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(String.format("符合筛选条件的报警历史总数:%s\n", data.getTotal()))
                .append(String.format("当条信息回传的报警历史数:%s\n", data.getCur()))
                .append(String.format("每条报警历史的数据长度:%s\n", data.getLength()))

                .append(line);

        for (int i = 0; i < data.getAlarlBeans().size(); i++) {
            int number = i + 1;

            Cmd40Bean.AlarlBean alarlBean = data.getAlarlBeans().get(i);
            stringBuilder.append(String.format("第%s条\n", number + ""))
                    .append(String.format("报警发生的时间:%s\n", alarlBean.getAlarmTime()))
                    .append(String.format("报警类型:%s\n", alarlBean.getAlarmType()))
                    .append(String.format("报警通道:%s\n", alarlBean.getAlarmTongdao()));
//                    .append(String.format("查询方式:%s\n", alarlBean.getModel()));
            if (alarlBean.getAlarmType().contains("开报")
                    || alarlBean.getAlarmType().contains("关报")
                    || alarlBean.getAlarmType().contains("变化报")) {
                if (alarlBean.getAlarmValue().contains("01")) {
                    stringBuilder.append(String.format("报警值:%s\n", "打开报警"));
                } else if (alarlBean.getAlarmValue().contains("02")) {
                    stringBuilder.append(String.format("报警值:%s\n", "关闭报警"));
                } else if (alarlBean.getAlarmValue().contains("03")) {
                    stringBuilder.append(String.format("报警值:%s\n", "变化报警"));
                } else {
                    stringBuilder.append(String.format("报警值(无定义):%s\n", alarlBean.getAlarmValue()));
                }


            } else {

                stringBuilder.append(String.format("报警值:%s\n", alarlBean.getAlarmValue()));

            }
            stringBuilder.append(line);

        }


        EventBus.getDefault().post(new DebugReadBean(stringBuilder.toString()));

        Log.e("xxxxxxxxxx", stringBuilder.toString());
    }


}





